//
//  LoginModle.swift
//  XMGG
//
//  Created by iDev on 7/2/17.
//  Copyright © 2017 iDev. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

struct LoginModle {
    var tu_account:String?
    var tu_password:String?
    var tu_loginDate:String?
    
    func loginRequest(){
        let parameters = [
            "req":[
                "tu_account":self.tu_account!,
                "tu_password":self.tu_password!,
                "tu_loginDate":self.tu_loginDate!
            ]
        ]
        Alamofire.request(APIURL+"api/user/login", method: .post, parameters: parameters, encoding: JSONEncoding.default).response { (response) in
            guard let data = HasCommonNetWorkError(response: response) else{
                self.loginFail(reason: "服务器无响应")
                return
            }
            self.handleData(data: data)
        }
    }
    
    private func handleData(data:Data){
        let json = JSON(data)
        guard let code = json["code"].int,let result = json["result"].dictionary else{
            print(json)
            loginFail(reason: "服务器无响应")
            return
        }
        guard let msg = result["msg"]?.string else{
            loginFail(reason: "服务器无响应")
            return
        }
        if code == 0 && msg == "user login success"{
            loginSuccess()
            return
        }
        if code == 1 && msg == "user login failed"{
            loginFail(reason: "用户名或密码错误")
            return
        }
        if code == 3 && msg == "user not exist"{
            loginFail(reason: "用户名或密码错误")
            return
        }
        loginFail(reason: "服务器正在维护")
    }
    
    func loginSuccess(){
        UserDefaults.standard.set(tu_account, forKey: kNSDefaultUsername)
        UserDefaults.standard.set(tu_password, forKey: kNSDefaultPwd)
        let notification = Notification(name: Notification.Name(rawValue: "loginResult"), object: true, userInfo: nil)
        NotificationCenter.default.post(notification)
    }
    
    func loginFail(reason:String){
        UserDefaults.standard.set(tu_account, forKey: kNSDefaultUsername)
        UserDefaults.standard.set(tu_password, forKey: kNSDefaultPwd)
        let notification = Notification(name: Notification.Name(rawValue: "loginResult"), object: false, userInfo: ["reason":reason])
        NotificationCenter.default.post(notification)
    }
    
    func isLeagal()->Bool{
        let user = self.tu_account ?? ""
        let pwd = self.tu_password ?? ""
        
//        let emailPattern = "^([a-zA-Z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
        let phonePattern = "^((13[0-9])|(17[0,6,7,8])|(15[^4,\\D])|(18[0,0-9])|(14[5,7]))\\d{8}$"
//        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [emailPattern])
        let phonePredicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [phonePattern])
        return (phonePredicate.evaluate(with:user))&&(pwd.characters.count>7&&pwd.characters.count<17)
    }
}
